package com.laoxu.test.rbacdemo.controller;


import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.laoxu.test.rbacdemo.common.PageRequest;
import com.laoxu.test.rbacdemo.common.Result;
import com.laoxu.test.rbacdemo.exception.AppException;
import com.laoxu.test.rbacdemo.model.SysRole;
import com.laoxu.test.rbacdemo.model.SysRoleMenu;
import com.laoxu.test.rbacdemo.service.SysRoleMenuService;
import com.laoxu.test.rbacdemo.service.SysRoleService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  角色控制器
 * </p>
 *
 * @author laoxu
 * @since 2020-08-09
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/api/role")
public class SysRoleController extends BaseController {
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysRoleMenuService roleMenuService;

    private String message;

    @GetMapping("/list")
    @RequiresPermissions("role:view")
    public Map<String, Object> roleList(PageRequest queryRequest, SysRole role) {
        return getDataTable(roleService.findRoles(role, queryRequest));
    }

    @GetMapping("check/{roleName}")
    public boolean checkRoleName(@NotBlank(message = "{required}") @PathVariable String roleName) {
        SysRole result = this.roleService.findByName(roleName);
        return result == null;
    }

    @GetMapping("menu/{roleId}")
    public List<String> getRoleMenus(@NotBlank(message = "{required}") @PathVariable String roleId) {
        List<SysRoleMenu> list = this.roleMenuService.getRoleMenusByRoleId(roleId);
        return list.stream().map(roleMenu -> String.valueOf(roleMenu.getMenuId())).collect(Collectors.toList());
    }

    @PostMapping("/add")
    @RequiresPermissions("role:add")
    public Result addRole(@RequestBody @Valid SysRole role) throws AppException {
        try {
            this.roleService.createRole(role);
            return new Result().ok("新增角色成功");
        } catch (Exception e) {
            message = "新增角色失败";
            log.error(message, e);
            throw new AppException(message);
        }
    }

    @PostMapping("/remove")
    @RequiresPermissions("role:delete")
    public Result deleteRoles(@NotBlank(message = "{required}") @RequestParam String roleIds) throws AppException {
        try {
            String[] ids = roleIds.split(StringPool.COMMA);
            this.roleService.deleteRoles(ids);
            return new Result().ok("删除角色成功");
        } catch (Exception e) {
            message = "删除角色失败";
            log.error(message, e);
            throw new AppException(message);
        }
    }

    @PostMapping("/modify")
    @RequiresPermissions("role:update")
    public Result updateRole(@RequestBody @Valid SysRole role) throws AppException {
        try {
            this.roleService.updateRole(role);
            return new Result().ok("修改角色成功");
        } catch (Exception e) {
            message = "修改角色失败";
            log.error(message, e);
            throw new AppException(message);
        }
    }

    @PostMapping("excel")
    @RequiresPermissions("role:export")
    public void export(PageRequest queryRequest,@RequestBody SysRole role, HttpServletResponse response) throws AppException {
        try {
            List<SysRole> roles = this.roleService.findRoles(role, queryRequest).getRecords();
            ExcelKit.$Export(SysRole.class, response).downXlsx(roles, false);
        } catch (Exception e) {
            message = "导出Excel失败";
            log.error(message, e);
            throw new AppException(message);
        }
    }
}
